<template>
  <!-- 计划选择商品组件 -->
  <el-dialog title="批量选择商品" :visible.sync="goodsVisible" :close-on-press-escape="true" width="70%" top="6vh"
    append-to-body :show-close="false">
    <div class="bgc-default pad-20">
      <div class="search-item">
        <label class="font-14"></label>
        <el-select class="select-class" v-model="searchListQuery.keywordType" style="width: 120px">
          <el-option label="商品名称" value="1"></el-option>
          <el-option label="商品货号" value="2"></el-option>
        </el-select>
        <el-input @keyup.enter.native="handleSearch" v-model.trim="searchListQuery.keyword" placeholder="请输入关键词"
          style="width: 280px;">
        </el-input>
        <label class="font-14 mar-l-20">商品分类：</label>
        <el-cascader v-model="categoryIds" :props="{ checkStrictly: true }" change-on-select placeholder="选择商品分类"
          :options="categoryData" class="special-input" clearable>
        </el-cascader>
        <label class="font-14 mar-l-20">商品来源：</label>
        <el-select v-model="goodsSource" style="width: 120px">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="(value, key) in dict.goodsSource" :key="key" :label="value" :value="key">
          </el-option>
          <el-option v-for="(item, index) in supplierList" :key="item.supplierId" :label="item.supplierName"
            :value="item.supplierId">
          </el-option>
        </el-select>
        <el-button-group class="mar-l-20">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetClick">重置</el-button>
        </el-button-group>
      </div>
      <!-- 全选、操作 -->
      <div>
        <div class="pad-t-15 font-14 v-align-c mar-b-10">
          <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="handleSelectCurrentPage"><span
              class="mar-l-20">当页全选</span></el-checkbox>
          <span class="pad-l-4 pad-r-4">|</span>
          <div>合计已选商品{{multipleSelection.length}}项</div>
        </div>
      </div>
      <div class="scroll-layer-box">
        <!-- 内容列表 -->
        <div class="table-container">
          <el-table ref="multipleTable" element-loading-text="加载中" style="width: 100%"
            header-cell-class-name="default-header" row-class-name="default-row" :data="goodsList"
            v-loading="listLoading" @selection-change="handleSelectionChange" :row-key="(row) => row.goodsId">
            <el-table-column width="50px" type="selection" fixed="left" :reserve-selection="true"></el-table-column>
            <el-table-column width="350px" label="商品信息" fixed="left">
              <template slot-scope="scope">
                <div class="flex v-align-c cursor-p mar-r-30">
                  <label><img :src="scope.row.mainImage" class="user-avatar cursor-p width-70 height-70"></label>
                  <div class="font-14 pad-l-10 v-align-h height-65">
                    <div class="goods-title">
                      <div class="line-2">
                        {{scope.row.title}}
                      </div>
                    </div>
                    <template v-if="scope.row.categoryName">
                      <span class="font-color-6 font-13">[{{scope.row.categoryName}}]</span>
                    </template>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column min-width="150px" label="货号">
              <template slot-scope="scope">
                {{scope.row.goodsCode}}
              </template>
            </el-table-column>
            <el-table-column min-width="150px" label="来源" prop="goodsNum">
              <template slot-scope="scope">
                <span v-if="scope.row.goodsSource !== 1">{{dict.goodsSource[scope.row.goodsSource]}}</span>
                <span v-if="scope.row.goodsSource == 1">{{scope.row.supplierName}}</span>
              </template>
            </el-table-column>
            <el-table-column width="150px" label="库存">
              <template slot-scope="scope">
                <div>
                  <span>可用：</span>
                  <el-button type="text" @click="seeStockDetail(scope.row)"
                    :disabled="scope.row.goodsSource === 3 ? true:false">
                    {{scope.row.remainStock}}
                  </el-button>
                </div>
                <div>
                  <span>占用：</span>
                  <el-button type="text" @click="seeStockDetail(scope.row)"
                    :disabled="scope.row.goodsSource === 3 ? true:false">
                    {{scope.row.stockInUse}}
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column min-width="140px" label="样品价">
              <template slot-scope="scope">
                ￥{{scope.row.specimenPrice}}
              </template>
            </el-table-column>
            <el-table-column min-width="140px" label="零售价">
              <template slot-scope="scope">
                ￥{{scope.row.sellPrice}}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 列表分页 -->
        <pagination v-show="total>0" :total="total" :page.sync="searchListQuery.currentPage"
          :limit.sync="searchListQuery.size" @pagination="pagingSelectGoodsByPlan" />
      </div>
      <div slot="footer" class="dialog-footer mar-t-10">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSureSelect(2)" :disabled="!(multipleSelection.length > 0)">仅选择勾选商品
        </el-button>
        <el-button type="primary" @click="handleSureSelect(3)" :disabled="!(searchResultAllGoodsIds.length > 0)">
          仅选择查询结果商品</el-button>
        <el-button type="primary" @click="handleSureSelect(1)">选择所有商品</el-button>
      </div>
    </div>
    <!-- 商品库存详情dialog -->
    <el-dialog title="商品库存详情" :visible.sync="openStockDetail" :center="true" top="5vh" width="850px" append-to-body>
      <goods-stock-detail :showFlag="openStockDetail" :goodsObj="selectGoodsObj" @callback="openStockDetail = false">
      </goods-stock-detail>
    </el-dialog>

  </el-dialog>
</template>

<script>
  import goodsStockDetail from '@/views/goods/components/goods-stock-detail'
  import {
    pagingSelectGoodsByPlan,
    getSelectGoodsIdsByPlan
  } from '@/api/goods/goods'
  import {
    getDictByGroupName
  } from '@/api/common/common'
  import {
    listGoodsCategory
  } from '@/api/goods/goods'
  import {
    listSupplier
  } from '@/api/user/supplier'
  import {
    getByEnterpriseId
  } from '@/api/user/enterprise'
  export default {
    components: {
      goodsStockDetail
    },
    props: {
      onSureCall: Function
    },
    data() {
      return {
        listLoading: false,
        planId: '',
        total: 0,
        goodsList: [],
        goodsSource: '',
        searchListQuery: {
          keywordType: '1',
          keyword: '',
          currentPage: 1,
          size: 10,
          selectionGoodsType: 1
        },
        goodsVisible: false,
        multipleSelection: [],
        openStockDetail: false,
        selectGoodsObj: {},
        categoryIds: [],
        // 商品的所有分类json
        categoryData: [],
        // 供应商数据
        supplierList: [],
        dict: {},
        allChecked: false,
        // 企业配置信息
        enterpriseConfig: {
          warehouseDeliverFlag: 0
        },
        // 查询结果的
        searchResultAllGoodsIds: []
      }
    },
    created() {
      getByEnterpriseId(this.getEnterpriseId()).then(response => {
        if (response.isError) return
        this.enterpriseConfig = response.data
      })
      this.initDict()
      this.listSupplier()
      this.listGoodsCategory()
    },
    methods: {
      // 打开选择计划商品
      // planId 计划id
      open(planId) {
        if (!planId) {
          this.msgError('计划id不能为空!')
          return
        }
        this.isSearchSaveLoadText = '仅选择查询结果商品'
        this.planId = planId
        this.goodsVisible = true
        this.pagingSelectGoodsByPlan()
      },
      // 设置查询条件
      setSearchListQuery() {
        this.searchListQuery.planId = this.planId
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        if (this.categoryIds.length > 0) {
          this.searchListQuery.categoryId = this.categoryIds[this.categoryIds.length - 1]
        }
        if (this.goodsSource !== '0' && this.goodsSource !== '1' && this.goodsSource !== '2' && this.goodsSource !==
          '3') {
          this.searchListQuery.supplierId = this.goodsSource
          this.searchListQuery.goodsSource = null
        } else {
          this.searchListQuery.supplierId = null
          this.searchListQuery.goodsSource = this.goodsSource
        }
      },
      pagingSelectGoodsByPlan() {
        this.listLoading = true
        this.setSearchListQuery()
        getSelectGoodsIdsByPlan(this.searchListQuery).then(reponse => {
          if (reponse.isError) return
          this.searchResultAllGoodsIds = reponse.data
        })
        pagingSelectGoodsByPlan(this.searchListQuery).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.total = response.data.total
          this.goodsList = response.data.records
          this.isAllCheckCurrentPage()
        })
      },
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.pagingSelectGoodsByPlan()
      },
      resetClick() {
        const originData = this.$options.data()
        this.searchListQuery = originData.searchListQuery
        this.categoryIds = []
        this.goodsSource = ''
        this.handleSearch()
      },
      // 获取供应商列表
      listSupplier() {
        listSupplier({
          enterpriseId: this.getEnterpriseId()
        }).then(response => {
          if (response.isError) return
          this.supplierList = response.data
        })
      },
      // 获取类目
      listGoodsCategory() {
        const enterpriseId = this.getEnterpriseId()
        listGoodsCategory(enterpriseId).then(response => {
          this.categoryData = response.data
        })
      },
      // 获取数据字典
      initDict() {
        getDictByGroupName('ProjectGoodsDTO').then(response => {
          Object.assign(this.dict, response.data)
        })
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
        this.isAllCheckCurrentPage()
      },
      // 确认选择
      // selectGoodsType:1-选择所有，2-选择勾选
      handleSureSelect(selectGoodsType) {
        if (selectGoodsType === 1) {
          this.onSureCall(selectGoodsType, [])
          this.handleCancel()
        } else if (selectGoodsType === 3) {
          // 选择查询结果s
          this.onSureCall(selectGoodsType, this.searchResultAllGoodsIds)
          this.handleCancel()
        } else {
          if (this.multipleSelection && this.multipleSelection.length > 0) {
            this.onSureCall(selectGoodsType, this.multipleSelection)
            this.handleCancel()
          } else {
            this.msgError('请选择商品')
          }
        }
      },
      // 取消
      handleCancel() {
        this.goodsVisible = false
        this.multipleSelection = []
        this.$refs.multipleTable.clearSelection()
        const originData = this.$options.data()
        this.searchListQuery = originData.searchListQuery
        this.categoryIds = []
        this.goodsSource = ''
      },
      // 查看库存明细
      seeStockDetail(row) {
        this.selectGoodsObj = row
        this.openStockDetail = true
      },
      // 选中当前页
      handleSelectCurrentPage(isChekced) {
        this.goodsList.forEach(item => {
          if (isChekced) {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          } else {
            this.$refs.multipleTable.toggleRowSelection(item, false)
          }
        })
      },
      // 校验当前页是否选中
      isAllCheckCurrentPage() {
        this.allChecked = false
        if (this.multipleSelection.length > 0 && this.goodsList.length > 0) {
          var currentSelectCount = 0
          this.goodsList.forEach(item => {
            var isExists = this.multipleSelection.some((selItem) => {
              return selItem.goodsId === item.goodsId
            })
            if (isExists) {
              currentSelectCount = currentSelectCount + 1
            }
          })
          if (this.goodsList.length === currentSelectCount) {
            this.allChecked = true
          }
        }
      }
    }
  }
</script>

<style lang="less" scoped>

</style>
